package com.nowcoder.community.controller;

import com.nowcoder.community.annotation.LoginRequire;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.LikeService;
import com.nowcoder.community.util.Constants;
import com.nowcoder.community.util.HostHolder;
import com.nowcoder.community.util.JsonBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("like")
public class LikeController {
    @Autowired
    LikeService likeService;

    @Autowired
    HostHolder hostHolder;

    @LoginRequire
    @PostMapping("/post")
    public JsonBody likePost(@RequestParam("entityId") int postId, @RequestParam("authorId") int userIdOfPost) {
        User user = hostHolder.getUser();
        likeService.like(user.getId(), userIdOfPost, Constants.ENTITY_TYPE_POST, postId);
        return JsonBody.ok("点赞成功!")
                .set("likeCount", likeService.countPostLike(postId))
                .set("likeStatus", likeService.getPostLikeStatus(user.getId(), postId));
    }

    @LoginRequire
    @PostMapping("/cancel/post")
    public JsonBody unlikePost(@RequestParam("entityId") int postId, @RequestParam("authorId") int userIdOfPost) {
        User user = hostHolder.getUser();
        likeService.unlike(user.getId(), userIdOfPost, Constants.ENTITY_TYPE_POST, postId);
        return JsonBody.ok("已取消赞.")
                .set("likeCount", likeService.countPostLike(postId))
                .set("likeStatus", likeService.getPostLikeStatus(user.getId(), postId));
    }

    @LoginRequire
    @PostMapping("/comment")
    public JsonBody likeComment(@RequestParam("entityId") int commentId, @RequestParam("authorId") int userIdOfComment) {
        User user = hostHolder.getUser();
        likeService.like(user.getId(), userIdOfComment, Constants.ENTITY_TYPE_COMMENT, commentId);
        return JsonBody.ok("点赞成功!")
                .set("likeCount", likeService.countCommentLike(commentId))
                .set("likeStatus", likeService.getCommentLikeStatus(user.getId(), commentId));
    }

    @LoginRequire
    @PostMapping("/cancel/comment")
    public JsonBody unlikeComment(@RequestParam("entityId") int commentId, @RequestParam("authorId") int userIdOfComment) {
        User user = hostHolder.getUser();
        likeService.unlike(user.getId(), userIdOfComment, Constants.ENTITY_TYPE_COMMENT, commentId);
        return JsonBody.ok("已取消赞.")
                .set("likeCount", likeService.countCommentLike(commentId))
                .set("likeStatus", likeService.getCommentLikeStatus(user.getId(), commentId));
    }
}
